<template>
	<uni-forms class="login-form" :modelValue="formData"  ref="loginForm" :rules="rule">
		<uni-forms-item name="account">
			<input
        v-model="formData.account"
				type="text"
				placeholder="请输入账号"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<input
        v-model="formData.password"
				type="text"
				placeholder="请输入密码"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<button class="submit-button" @click="login()">登录</button>
	</uni-forms>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { showFailToast } from '../../../utils';
import { uniFetch } from '../../../apis/uni-fetch';
import { useMyStore } from '../../../stores';
import { getLoginUser, loginRequest } from '../../../apis/user';

  const loginForm = ref()
  const formData = reactive({
    account:'',
    password:''
  })
  const rule = reactive({
    account:{
      rules:[{
        required:true,
        errorMessage:'请输入账号'
      },{
        pattern:'^[a-zA-Z0-9]{6,8}$',
        errorMessage:'账号格式错误'
      }]
    },
    password:{
      rules:[{
        required:true,
        errorMessage:'请输入密码'
      },{
        pattern:'^\\d{6}$',
        errorMessage:'密码格式错误'
      }]
    }
  })
  const login = async () => {
    const store = useMyStore()
    try{
      let isOk = await loginForm.value.validate();

       loginRequest(formData, async res => {
        console.log('loginRequest',res);
        if(res.code === 200){
          store.setToken(res.data)
          await getLoginUser(res => {
            store.setLoginUser(res)
          })
          uni.switchTab({
            url:'/pages/task/index'
          })
        }else{
          showFailToast(res.msg)
        }
      })
    }catch(e){
      console.log('loginRequest发生异常',e);
      return
    }

  }
</script>

<style lang="scss" scoped>
	@import './styles.scss';
</style>
